<template>
  <div class="category-container">
    <div class="banner">
      <div class="banner-content">
        <h1>{{ categoryName || '全部分类' }}</h1>
        <p>探索这个分类下的所有文章</p>
      </div>
    </div>
    
    <div class="main-content">
      <div class="blog-list">
        <Spin :spinning="loading" tip="加载中...">
          <div v-if="blogs.length > 0">
            <div v-for="blog in blogs" :key="blog._id" class="blog-card">
              <router-link :to="`/blog/${blog._id}`" class="blog-link">
                <h3 class="blog-title">{{ blog.title }}</h3>
                <p class="blog-summary">{{ blog.summary }}</p>
                <div class="blog-meta">
                  <span class="blog-date">{{ blog.date }}</span>
                  <span class="blog-category">分类：{{ blog.category.name }}</span>
                </div>
              </router-link>
            </div>
            
            <div class="load-more" v-if="hasMore">
              <button @click="loadMore" :disabled="loading">{{ loading ? '加载中...' : '加载更多' }}</button>
            </div>
          </div>
          
          <div v-else-if="!loading" class="empty-state">
            <p>暂无相关文章</p>
          </div>
        </Spin>
      </div>
      
      <div class="sidebar">
        <div class="categories">
          <h3>所有分类</h3>
          <Spin :spinning="loadingCategories" size="small">
            <ul v-if="allCategories.length > 0">
              <li v-for="cat in allCategories" :key="cat._id">
                <router-link :to="`/category/${cat.id}`" :class="{ active: cat.id === categoryId }">
                  {{ cat.name }} ({{ cat.count }})
                </router-link>
              </li>
            </ul>
            <div v-else-if="!loadingCategories" class="empty-state small">
              <p>暂无分类数据</p>
            </div>
          </Spin>
        </div>
        
        <div class="tags">
          <h3>热门标签</h3>
          <Spin :spinning="loadingTags" size="small">
            <div v-if="tags.length > 0" class="tag-list">
              <Tag v-for="tag in tags" :key="tag._id" color="blue">
                <router-link :to="`/tag/${tag.id}`">{{ tag.name }}</router-link>
              </Tag>
            </div>
            <div v-else-if="!loadingTags" class="empty-state small">
              <p>暂无标签数据</p>
            </div>
          </Spin>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { Tag, Spin } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import { useBlogStore } from '../stores/blog'

const route = useRoute()
const router = useRouter()
const categoryId = ref(route.params.id || '')
const categoryName = ref('')
const loading = ref(false)

// 使用 Pinia store
const blogStore = useBlogStore()

// 博客数据
const blogs = ref([])

// 加载更多相关
const hasMore = ref(false)
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 计算属性 - 从 store 获取数据
const allCategories = computed(() => blogStore.cachedCategories)
const tags = computed(() => blogStore.cachedTags)
const loadingCategories = computed(() => blogStore.isCategoriesLoading)
const loadingTags = computed(() => blogStore.isTagsLoading)

// 根据 ID 获取分类信息
const getCurrentCategory = () => {
  const categories = blogStore.cachedCategories
  const category = categories.find(cat => cat.id === categoryId.value)
  if (category) {
    categoryName.value = category.name
  } else {
    // 如果没有找到分类，设置为空字符串，避免显示"全部分类"
    categoryName.value = ''
  }
  return category
}

// 获取分类下的文章
const fetchCategoryArticles = async () => {
  loading.value = true
  try {
    const data = await blogStore.getArticles({
      category: categoryId.value,
      page: page.value,
      pageSize: pageSize.value
    })
    
    if (data && data.list) {
      blogs.value = data.list
      total.value = data.total
      hasMore.value = blogs.value.length < total.value
    }
  } catch (error) {
    console.error('获取分类文章异常:', error)
  } finally {
    loading.value = false
  }
}

// 获取所有分类
const fetchAllCategories = async () => {
  try {
    await blogStore.getCategories()
  } catch (error) {
    console.error('获取分类列表异常:', error)
  }
}

// 获取热门标签
const fetchTags = async () => {
  try {
    await blogStore.getTags()
  } catch (error) {
    console.error('获取标签列表异常:', error)
  }
}

// 加载更多文章
const loadMore = () => {
  page.value++
  fetchMoreArticles()
}

// 获取更多文章
const fetchMoreArticles = async () => {
  loading.value = true
  try {
    const data = await blogStore.getArticles({
      category: categoryId.value,
      page: page.value,
      pageSize: pageSize.value
    })
    
    if (data && data.list) {
      blogs.value = [...blogs.value, ...data.list]
      total.value = data.total
      hasMore.value = blogs.value.length < total.value
    }
  } catch (error) {
    console.error('获取更多文章异常:', error)
  } finally {
    loading.value = false
  }
}

// 监听路由参数变化
watch(() => route.params.id, (newId) => {
  if (newId !== categoryId.value) {
    categoryId.value = newId || ''
    page.value = 1 // 重置页码
    getCurrentCategory() // 获取分类信息
    fetchCategoryArticles() // 重新获取该分类下的文章
  }
})

// 监听分类数据变化，确保分类数据加载完成后能正确设置分类名称
watch(() => blogStore.cachedCategories, (newCategories) => {
  if (newCategories.length > 0 && categoryId.value && !categoryName.value) {
    getCurrentCategory()
  }
}, { immediate: true })

// 初始化数据
onMounted(async () => {
  if (route.params.id) {
    categoryId.value = route.params.id
  }
  
  // 先获取分类列表，然后获取当前分类信息
  await fetchAllCategories()
  
  // 确保分类数据加载完成后再获取当前分类信息
  if (blogStore.cachedCategories.length > 0) {
    getCurrentCategory()
  }
  
  fetchCategoryArticles() // 获取分类文章
  fetchTags() // 获取热门标签
})
</script>

<style scoped>
.category-container {
  width: 100%;
  min-height: 100vh;
}

.banner {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
  padding: 80px 0;
  text-align: center;
  position: relative;
  overflow: hidden;
}

.banner::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('') repeat;
}

.banner-content {
  position: relative;
  z-index: 1;
  max-width: 800px;
  margin: 0 auto;
}

.banner-content h1 {
  font-size: 2.8em;
  margin-bottom: 20px;
  font-weight: 700;
  letter-spacing: -0.5px;
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.banner-content p {
  font-size: 1.3em;
  opacity: 0.9;
  margin-bottom: 0;
  text-shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
}

.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;
  display: flex;
  gap: 40px;
}

.blog-list {
  flex: 3;
}

.blog-card {
  background: white;
  border-radius: 12px;
  padding: 32px;
  margin-bottom: 32px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  border: 1px solid rgba(0, 0, 0, 0.05);
  position: relative;
  overflow: hidden;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  background-color: rgba(0, 0, 0, 0.02);
  border-radius: 12px;
  margin: 20px 0;
}

.empty-state p {
  color: rgba(0, 0, 0, 0.45);
  font-size: 16px;
}

.empty-state.small {
  padding: 20px;
  margin: 10px 0;
}

.empty-state.small p {
  font-size: 14px;
}

.load-more {
  text-align: center;
  margin: 30px 0;
}

.load-more button {
  background: #1890ff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.load-more button:hover {
  background: #40a9ff;
}

.load-more button:disabled {
  background: #bae7ff;
  cursor: not-allowed;
}

.blog-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.blog-card:hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  transform: translateY(-4px);
  border-color: rgba(79, 172, 254, 0.2);
}

.blog-card:hover::before {
  opacity: 1;
}

.blog-link {
  color: inherit;
  text-decoration: none;
  display: block;
  transition: color 0.3s ease;
}

.blog-title {
  font-size: 1.8em;
  margin-bottom: 16px;
  color: #4facfe;
  font-weight: 600;
  line-height: 1.4;
  transition: color 0.3s ease;
}

.blog-link:hover .blog-title {
  color: #00f2fe;
}

.blog-summary {
  color: #666;
  margin-bottom: 20px;
  line-height: 1.7;
  font-size: 1.05em;
}

.blog-meta {
  display: flex;
  gap: 20px;
  font-size: 0.95em;
  color: #999;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.blog-date,
.blog-category {
  display: flex;
  align-items: center;
  gap: 6px;
}

.sidebar {
  flex: 1;
}

.categories,
.tags {
  background: white;
  border-radius: 12px;
  padding: 28px;
  margin-bottom: 28px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.categories:hover,
.tags:hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  border-color: rgba(79, 172, 254, 0.2);
}

.categories h3,
.tags h3 {
  margin-bottom: 20px;
  font-size: 1.3em;
  font-weight: 600;
  color: #333;
  position: relative;
  padding-bottom: 12px;
}

.categories h3::after,
.tags h3::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 40px;
  height: 3px;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  border-radius: 3px;
}

.categories ul {
  list-style: none;
  padding: 0;
}

.categories li {
  margin-bottom: 16px;
}

.categories a {
  color: #666;
  text-decoration: none;
  transition: all 0.3s ease;
  font-size: 0.95em;
  display: inline-block;
  position: relative;
  padding-left: 20px;
}

.categories a::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 6px;
  height: 6px;
  background: #4facfe;
  border-radius: 50%;
  opacity: 0.5;
  transition: opacity 0.3s ease;
}

.categories a:hover {
  color: #4facfe;
  transform: translateX(4px);
}

.categories a:hover::before {
  opacity: 1;
}

.categories a.active {
  color: #4facfe;
  font-weight: 500;
}

.categories a.active::before {
  opacity: 1;
  transform: translateY(-50%) scale(1.2);
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.tag-list a {
  text-decoration: none;
  transition: all 0.3s ease;
  font-size: 0.9em;
}

.tag-list a:hover {
  transform: scale(1.05);
}

/* 加载更多按钮样式 */
.load-more {
  text-align: center;
  padding: 40px 0;
}

.load-more button {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  font-size: 1em;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(79, 172, 254, 0.3);
}

.load-more button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(79, 172, 254, 0.4);
}

.load-more button:active {
  transform: translateY(0);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .banner {
    padding: 60px 0;
  }
  
  .banner-content h1 {
    font-size: 2.2em;
  }
  
  .banner-content p {
    font-size: 1.1em;
  }
  
  .main-content {
    flex-direction: column;
    gap: 32px;
    padding: 32px 16px;
  }
  
  .blog-card {
    padding: 24px;
    margin-bottom: 24px;
  }
  
  .blog-title {
    font-size: 1.5em;
  }
  
  .categories,
  .tags {
    padding: 24px;
    margin-bottom: 24px;
  }
}

@media (max-width: 480px) {
  .banner {
    padding: 50px 0;
  }
  
  .banner-content h1 {
    font-size: 2em;
  }
  
  .main-content {
    padding: 24px 16px;
  }
  
  .blog-meta {
    flex-direction: column;
    gap: 8px;
  }
}

/* 动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.blog-card {
  animation: fadeInUp 0.5s ease-out;
}

.blog-card:nth-child(2) {
  animation-delay: 0.1s;
}

.blog-card:nth-child(3) {
  animation-delay: 0.2s;
}
</style>